import logging
from django.db import DatabaseError
from django.middleware.common import MiddlewareMixin
from utils.result import R
from utils.exceptions import BusinessException

logger = logging.getLogger('django')


class ExceptionMiddleware(MiddlewareMixin):
    """
    统一异常处理中间件
    process_exception() 这个函数在视图函数向外抛出错误时将其捕获
    """
    @staticmethod
    def process_exception(request, exception):
        """
        统一异常处理
        :param request: 请求对象
        :param exception: 异常对象
        :return:
        """
        if isinstance(exception, BusinessException):
            # 业务异常处理
            if exception.data is not None:
                return R.error(exception.enum_cls).data(exception.data)
            else:
                return R.error(exception.enum_cls).data()

        elif isinstance(exception, DatabaseError):
            r = R.db_error().data()
            logger.error('异常处理器收到信息：数据库异常', exc_info=True)
            return r

        elif isinstance(exception, Exception):
            # 服务器异常处理
            r = R.server_error().data()
            logger.error('异常处理器收到信息：服务器异常', exc_info=True)
            return r

        return None
